package com.beater.global.auth0;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * Token 生产与校验
 * 
 * @author 罗涛
 *
 */
public class TokenAutho {
	/** token 失效时间15天 */
	public final static long EXPIRE_TIME = 15 * 24 * 60 * 60 * 1000;
	/** token 私钥 */
	public final static String TOKEN_SECURE = "ABCabc123321456654";

	/**
	 * 生成token,15天后失效
	 * 
	 * @param uid
	 * @param uname
	 * @return
	 */
	public static String createToken(String uid, String uname) {
		try {
			/** 过期时间 */
			Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
			/** 私钥及加密算法 */
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECURE);
			/** 设置头部信息 */
			Map<String, Object> header = new HashMap<String, Object>();
			header.put("type", "JWT");
			header.put("alg", "HS256");
			// 附带userId,userName
			return JWT.create().withHeader(header)
					.withClaim("loginName", uname).withClaim("uid", uid)
					.withExpiresAt(date).sign(algorithm);

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
	
	/**
	 * 校验token
	 * @param token
	 * @return
	 */

	public static boolean verifyToken(String token) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECURE);
			JWTVerifier jVerifier = JWT.require(algorithm).build();
			jVerifier.verify(token);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
	
	/**
	 * 获取uid
	 * @param token
	 * @return
	 */
	public static String getUid(String token){
		try {
			DecodedJWT jwt = JWT.decode(token) ;
			return jwt.getClaim("uid").asString() ;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null ;
		}
	}
	
	/**
	 * 获取uname
	 * @param token
	 * @return
	 */
	public static String getUname(String token){
		try {
			DecodedJWT jwt = JWT.decode(token) ;
			return jwt.getClaim("loginName").asString() ;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null ;
		}
	}

}
